<template>
  <div class="layout">
    <div style="display: flex; justify-content: center">
      <Breadcrumb class="breadcrumb" :crumbs="crumbs"></Breadcrumb>
    </div>
    <div class="content">
      <p class="title">服务机构入驻</p>
      <el-form ref="ruleForm" :model="formData" :rules="rules" label-width="136px" class="servce_form">
        <el-form-item label="服务类型：" prop="servceType">
          <el-cascader 
            ref="servceType"
            style="width: 100%"
            size="medium" 
            placeholder="请选择服务类型" 
            :options="queryList" 
            v-model="formData.servceType" 
            @change="handlecategoryChange"
            :props="{ multiple: true }"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="服务描述：" prop="servceDes">
          <el-input type="textarea" :show-word-limit="true" :autosize="{ minRows: 4, maxRows: 4 }" class="textare" placeholder="请输入服务描述" resize="none"  v-model="formData.servceDes"  maxlength="500"></el-input>
        </el-form-item>
        <el-form-item label="运营时间：" required>
          <el-col :span="9">
            <el-form-item prop="startTime">
              <el-time-select placeholder="开始时间" v-model="formData.startTime" :picker-options="{start: '00:00', step: '00:15', end: '24:00'}">
              </el-time-select>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="2">～</el-col>
          <el-col :span="11">
            <el-form-item prop="endTime">
              <el-time-select placeholder="结束时间" v-model="formData.endTime" :picker-options="{start: '00:00', step: '00:15', end: '24:00', minTime: formData.startTime}">
              </el-time-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="服务状态：" prop="servceStatus">
          <el-select v-model="formData.servceStatus" placeholder="请选择服务状态">
            <el-option label="运营中" value="0"></el-option>
            <el-option label="休息中" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务地址：" prop="preAddr" class="_address">
          <div class="addressBtn" @click="openMap" v-show="!formData.preAddr">
            <i class="_icon"></i>
            <span>选择地址</span>
          </div>
          <el-input placeholder="请点击选择地址" v-model="formData.preAddr" maxlength="50" @click="openMap" class="mapInput" v-show="formData.preAddr" :disabled="true"></el-input>
          <div class="addressBtn" @click="openMap" style="position: absolute;right:0;top:0" v-show="formData.preAddr">
            <i class="_icon"></i>
            <span>重新选择</span>
          </div>
        </el-form-item>
        <el-form-item label="详细地址：" v-show="formData.preAddr">
          <el-input v-model="formData.address" maxlength="50"></el-input>
        </el-form-item>
        
        <el-form-item label="对外服务电话：" prop="mobeil">
          <el-input placeholder="请输入对外服务电话" v-model="formData.mobeil"></el-input>
        </el-form-item>
        <el-form-item label="相关图片：" prop="picture">
          <addImgUpload @changeImgUp="changeImgUpLicense"></addImgUpload>
        </el-form-item>
        <el-form-item label="入驻材料：" prop="fileUrl">
          <addUpload @changeUp="changeUp"></addUpload>
        </el-form-item>
        <el-form-item  prop="readChecked">
          <el-checkbox v-model="formData.readChecked">
            <div class="read">我已阅读并同意<a href="javascript:;">《裕华区政府企业服务用户注册协议》</a></div>
          </el-checkbox>
        </el-form-item>
        <div class="btn_list">
          <Buttons :buttons="buttons_cancle" @goBack="goBack"></Buttons>
          <Buttons v-if="butLoing" :buttons="buttons_butLoing" @none="''"></Buttons>
          <Buttons v-else :buttons="buttons_submit" @submit="submitForm"></Buttons>
        </div>
      </el-form>
    </div>
    <!-- 详细地址-遮罩层开始 -->
    <div class="addressShadow" v-show="isOpen">
      <div class="addressShadow-content">
        <div class="addressShadow-main">
          <div class="addressShadow-close" @click="closeMap">×</div>
          <Map @closeMap="getFromData" :publicData="publicData"></Map>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Breadcrumb from "@/components/breadcrumb";
import addImgUpload from "./components/qtImgUpload";
import addUpload from "./components/qtUpload";

import { getsettled, getArea, getqueryList } from "@/common/api/service.js";

import Map from "./components/map"

import { isLogin } from "@/utils/util.js";

import serviceEnter from '@/formRules/service/serviceEnter.js'

export default {
  mixins: [serviceEnter],
  name: "service",
  components: { Breadcrumb, addImgUpload, addUpload, Map },
  data() {
    return {
      buttons_cancle:[{text:"返回",size:"l",type:"normal",method:"goBack"}],
      buttons_butLoing:[{text:"提交中....",size:"l",type:"success",method:"none"}],
      buttons_submit:[{text:"确定",size:"l",type:"success",method:"submit"}],
      publicData:{
        searchInput:true, //搜索框打开
        longitude:this.longitude, //当前选择的经纬度
        latitude:this.latitude
      },
      // 地图相关开始
      mapLoading:false,
      mapSearch:"",
      _map:{},
      isOpen:false,
      city:"",
      isFirstClick:null,
      // 地图相关结束
      // 准备上传加载图标
      loading:null,
      crumbs: [
        {
          label: "门户首页",
          value: "index",
        },
        {
          label: "服务市场",
          value: "service",
        },
        {
          label: "服务机构入驻",
          value: "",
          choose: true,
        },
      ],
      companyId: '',
      companyName: '',
      // 地区的数据
      areaData: [],
      val: [],
      // 1级类型目录
      queryList: [],
      typeList: [],
      butLoing: false
    };
  },
  methods: {
    // map组件的值
    getFromData(data){
      for(let key in data){
        this.formData[key] = data[key];
      }
      this.closeMap();
      this.mapLoading = false;
    },
    // 给时间输入框添加只读属性
    setInputReadonly(){
      let inputs = window.document.getElementsByClassName("el-input__inner");
      inputs[1].setAttribute("readonly","true");
      inputs[2].setAttribute("readonly","true");
    },
    // 点击触发事件
    openMap(){
      this.isOpen = !this.isOpen;
    },
    // 地图对话框点击取消
    closeMap(){
      this.isOpen = false;
    },
    // 搜索框点击取消
    closeSearch(){
      this.mapSearch = "";
    },
    // 地图对话框点击确认
    okMap(){
      console.log(this.formData.address.trim());
      if(this.formData.address.trim() == ""){
        this.$message.error("请点击选择地址");
        return;
      }
      this.isOpen = false;
    },
    // 地图相关结束
    changeImgUpLicense(obj) { // 图片上传成功
      console.log('obj', obj)
      this.formData.picture= obj
      this.$refs["ruleForm"].validateField("picture");
    },
    changeUp(obj) {
      obj = obj.map(e => {
         return {
          fileName: e.fileName,
          fileType: e.fileType,
          fileUrl: e.fileUrl
        }
      })
      // console.log('obj' , obj)
      this.formData.fileUrl = obj
      // this.formData.fileUrl = obj.map(e => e.batchId).join(",")
      this.$refs["ruleForm"].validateField("fileUrl")
    },
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if(!valid) return false
        let attachment = this.formData.fileUrl.concat(this.formData.picture)
        let itemType = this.typeList.join(',')
        console.log('arr', itemType)
        let obj = {
          agencyName: this.companyName,
          address: this.formData.address,
          preAddr: this.formData.preAddr,
          areaCode: this.formData.areaCode,
          areaName: this.formData.areaName,
          attachment,
          cityCode: this.formData.cityCode,
          cityName: this.formData.cityName,
          corporationId: this.companyId,
          itemType,
          phoneNumber: this.formData.mobeil,
          provinceCode: this.formData.provinceCode,
          provinceName: this.formData.provinceName,
          runtimeBegin: this.formData.startTime,
          runtimeEnd: this.formData.endTime,
          serviceDesc: this.formData.servceDes,
          serviceState: this.formData.servceStatus,
          longitude: this.formData.longitude,
          latitude:this.formData.latitude
        }
        this.butLoing = true
        // console.log('提交', obj)
        this.getsettled(obj)
      });
    },
    // 提交入驻接口
    async getsettled(obj){
      const updataLoading = this.$loading({
        lock: true,
        text: '正在上传,请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      let res = await getsettled(obj);
      console.log('res', res)
      if(res.status == 200) {
        this.$message.success('提交成功')
        updataLoading.close();
        setTimeout(() => {
          this.$router.push('service')
        }, 2000)
      }
      if(res.status == 500){
        this.$message.error(res.message)
        updataLoading.close();
      }
      this.butLoing = false;
      updataLoading.close();
    },
    // 地区数据
    async getArea() {
      let res = await getArea();
      if (res.code == 200) {
        // console.log('res.data',res.data)
        this.areaData = res.data;
      }
    },
    handleTreeChange(e) {
      // let nodesObj = this.$refs['cascaderAddr'].currentLabels
      // console.log('nodesObj', e)
      // 数姐长度是2的情况就是说明直辖市,省code、省name都是用市的名字就可以了
      if(e.length ==2) {
        let one = this.areaData.filter(item => item.id == e[0])
        // console.log('one', one, one[0].children)
        let children = []
        if(one.length) {
          children = one[0].children.filter(item => item.id == e[1])
        }
        // console.log('children', children)
        // 编码
        this.formData.provinceCode = e[0];
        this.formData.cityCode = e[0];
        this.formData.areaCode = e[1];
        // 名称
        this.formData.provinceName = one[0].label
        this.formData.cityName = one[0].label
        this.formData.areaName = children[0].label
        // console.log('this.formData',  this.formData)
      }else {
        let one = this.areaData.filter(item => item.id == e[0])
        let twochildren = []
        if(one.length) {
          twochildren = one[0].children.filter(item => item.id == e[1])
        }
        let threechildren = twochildren[0].children.filter(item => item.id == e[2])
        // 编码
        this.formData.provinceCode = e[0];
        this.formData.cityCode = e[1];
        this.formData.areaCode = e[2];
        // 名称
        this.formData.provinceName = one[0].label
        this.formData.cityName = twochildren[0].label
        this.formData.areaName = threechildren[0].label
      }
    },
    // 查询1级类目列表
    async getqueryList() {
      let res = await getqueryList();
      console.log('getqueryList', res, res.status)
      if (res.status == 200) {
        // console.log('res.data',res.result)
        // this.areaData = res.data;
        this.getchildren(res.result)
        this.queryList = res.result
      }
    },
    // 处理类目数据
    getchildren(data) {
      // console.log('data', data)
      var IShave = false
      data.forEach(item => {
        // item.key = item.id
        item.label = item.categoryName
        item.value = item.categoryId
        if (item.children != null) {
          IShave = true
        } else {
          item.children = null
        }
        if (IShave) {
          if(item.children) {
            this.getchildren(item.children)
          }
        }
      })
    },
    // 获取类型的数据
    handlecategoryChange(e){
      // console.log('e', e)
      if(e && e.length) {
        let arr = e.map(item => item.join('_'))
        console.log('arr', arr)
        this.typeList = arr
      }
    },
    /**
     * 返回上一页
     */
    goBack(){
      this.$router.back();
    }
  },
  mounted() {
    // this.setMap();
    // 如果没有登录进来就跳转到登录页
    if(!isLogin()){
      // this.$message.error('请先登录！！')
      setTimeout(() => {
        this.$router.push({path: 'login'});
      }, 1000);
    } else {
      // 通过路由获取产品id
      if (this.$route.query.companyId) {
        this.companyId = this.$route.query.companyId;
        this.companyName = this.$route.query.companyName;
      }else {
        let info = JSON.parse(localStorage.getItem('companyInfo'))
        // console.log('info', info)
        this.companyId = info.id;
        this.companyName = info.companyname;
        // console.log('info', this.companyId, this.companyName)
      }
    };
    this.setInputReadonly();
  },
  activated() {},
  created() {
    // console.log(111);
    this.getArea()
    this.getqueryList()
  },
};
</script>

<style lang="scss" scoped>
.divtype{
  display: flex;
  margin-top: 10px;
}
.divtype >div{
  margin-right: 10px;
  border: 1px solid #ddd;
  padding: 10px;
  line-height: 10px;
  position: relative;
  .closed{
    width: 15px;
    height: 15px;
    position: absolute;
    right: -5px;
    top: -8px;
    img{
      width: 100%;
      height: 100%;
    }
  }
}
.breadcrumb {
  width: 1200px;
  margin: 20px 0;
}

.layout {
  min-height: 100vh;
  position: relative;
  padding-bottom: 150px;
  box-sizing: border-box;
}

.content {
  width: 800px;
  padding: 47px 0;
  margin: auto;
  text-align: left;
  
  .title {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 40px;
    color: #045DB9;
  }
  .read {
    a {
      color: #045DB9;
    }
  }
  .btn_list {
    display: flex;
    align-items: center;
    padding-left: 136px;
    margin-top: 20px;
    >div{
      margin-right: 20px;
    }
    >:nth-last-child(1){
      margin-right: 0px;
    }
    a {
      width: 120px;
      height: 40px;
      text-align: center;
      line-height: 40px;
      font-size: 14px;
      border-radius: 3px;
      background-color: #F1F2F4;
      color: #045DB9;
      &.submit {
        background-color: #045DB9;
        color: #fff;
        margin-left: 20px;
      }
    }
  }
}

.footer {
  position: absolute;
  bottom: 0;
  width: 100%;
}
</style>
<style lang="scss">
.content{
    textarea::-webkit-input-placeholder{
      font-size: 14px;
      font-family: 'Avenir', Helvetica, Arial, sans-serif;
    }
  }
</style>

<!-- 地图开始 -->
<style  lang="scss" scoped>
._address{
  position: relative;
  .addressDiv{
    width: 100%;
    height: 40px;
    border: 1px solid #dcdfe6;
    border-radius: 3px;
    color: #c0c4cc;
    text-indent: 35px;
    cursor: pointer;
    &:hover{
      border: 1px solid #c0c4cc;
    }
  }
  .addressOpenMap{
    width: 100%;
    height: 40px;
    position: absolute;
    right: 0;
    background-color: transparent;
    z-index: 100;
  }
}
.addressBtn{
  width: 118px;
  height: 40px;
  background-color: #045DB9;
  border-radius: 3px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  ._icon{
    background: url(../../assets/image/service/rightArrow_white.png) no-repeat center;
    width: 16px;
    height: 23px;
  }
  >span{
    color:#fff;
    font-family: "PingFangSC-Regular";
    font-size: 16px;
    margin-left: 12px;
  }
}
.map{
  width: 40px;
  height: 40px;
  position: absolute;
  top:0;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  ._icon{
    background: url(../../assets/image/service/rightArrow.png) no-repeat center;
    width: 24px;
    height: 24px;
  }
}
.el-dialog{
  z-index: 999 !important;
  .searchBox{
    position: absolute;
    z-index: 9999;
    width: 30%;
    left: 100px;
    top: 120px;
    .el-input{
      width: 100%;
    }
      ._icon{
        font-size: 18px;
        position: absolute;
        right: 10px;
        top: 11px;
        color: #999;
      }
  }
}
#container {
  position: relative;
  margin: 0 auto;
  width:100%; height: 100%; 
    .el-input{
      z-index: 99999;
      position: relative;
      width: 30%;
    }
      ._icon{
        font-size: 18px;
        position: absolute;
        right: 10px;
        top: 11px;
        color: #999;
        z-index: 99999;
      }
}  
.mapTitle{
  margin-left:50px;
  padding: 10px 0;
  font-size: 16px;
}
// 最外层遮罩层
.addressShadow{
  background-color: rgba(0,0,0,.5);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 100;
  .addressShadow-content{
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 200;
    .addressShadow-main{
      position: relative;
      width: 914px;
      height: 550px;
      background-color: #fff;
      .addressShadow-close{
        width: 34px;
        height: 34px;
        background-color: transparent;
        border: 1px solid #fff;
        border-radius: 50%;
        position: absolute;
        right: -57px;
        top: -45px;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 30px;
        color: #fff;
        cursor: pointer;
        font-weight: 200;
      }
      .addressShadow-search{
        position: absolute;
        top: 26px;
        left: 40px;
        display: flex;
        z-index: 99999;
        > input{
          border: 0;
          border-radius: 0;
          width: 368px;
          height: 40px;
          background: #FFFFFF;
          font-size: 16px;
          box-shadow: 0px 2px 4px 0px rgba(0,0,0,0.25);
          outline:none;
          text-indent: 14px;
          font-family: "SourceHanSansSC-Regular";
        }
        > button{
          border: 0;
          width: 77px;
          height: 40px;
          background: #045DB9;
          box-shadow: 2px 2px 4px 0px rgba(0,0,0,0.25);
          color: #fff;
          font-size: 16px;
          cursor: pointer;
          > span{
            width: 32px;
            height: 24px;
            font-family: "SourceHanSansSC-Regular";
            font-size: 16px;
            color: #FFFFFF;
            text-align: center;
            font-weight: 400;
          }
        }
        .search-close{
          width: 20px;
          height: 20px;
          background: url(../../assets/image/service/searchClose.png
          ) no-repeat center;
          position: absolute;
          top: 9px;
          right: 89px;
          cursor: pointer;
        }
      }
    }
  }
}
// 地图输入框的样式
// .mapInput{
//   >>> .el-input__inner{
//     text-indent: 20px;
//   }
// }
// marker的样式
.marker{
  width: 30px;
  height: 30px;
  border: 1px solid #1d8eff;
  border-radius: 50%;
  background-color: transparent;
  display: flex;
  justify-content: center;
  align-items: center;
  .marker-main{
    width: 15px;
    height: 15px;
    background-color: #1d8eff;
    border-radius: 50%;
  }
}
</style>
<!-- 地图结束 -->